import { DomUtil, Control, DomEvent } from 'leaflet'
/**
 *@classdesc 自定义leaflet的控制组件
 *@description 折叠组件
 * @author Niyang
 */
export const Collapse = Control.extend({
    options: {
        position: 'bottomleft',
        foldIcon: undefined,
        unfoldIcon: undefined,
        state: 1
    },
    /**
     * @description 重写add函数
     * @param {L.Map} map
     * @returns Element
     */
    onAdd (map) {
        const clazz = 'leaflet-control-collapse'
        const container = DomUtil.create('div', clazz + ' leaflet-bar')
        this._createIcon(container, this._onCollapse)
        return container
    },
    /**
     * @description 折叠icon及事件绑定
     * @param {Element} container
     * @param {Function} fn
     */
    _createIcon (container, fn) {
        const opts = this.options
        const iconClazzs = [opts.unfoldIcon, opts.foldIcon]
        const iEl = DomUtil.create('i', iconClazzs[opts.state], container)

        iEl.setAttribute('role', 'collapse')
        iEl.setAttribute('aria-hidden', 'true')

        DomEvent.disableClickPropagation(iEl)
        DomEvent.on(iEl, 'click', DomEvent.stop)
        DomEvent.on(iEl, 'click', fn, this)
    },
    /**
     * @description 事件处理
     * @param {Event} e
     */
    _onCollapse (e) {
        const iconClazzs = [this.options.unfoldIcon, this.options.foldIcon]
        this.options.state = this.options.state === 1 ? 0 : 1
        e.target.setAttribute('class', iconClazzs[this.options.state])
        this._map.fire('collapse')
    }
})

export function collapse (options) {
    return new Collapse(options)
}
